package subscribe

import (
	"encoding/json"
	"fmt"
	"longmen/server/config/global"
	"longmen/server/internal/rpc/tencentim/api"
	"longmen/server/internal/rpc/tencentim/cache"
	"longmen/server/internal/rpc/tencentim/chat"
	imsdk2 "longmen/server/internal/rpc/tencentim/imsdk"
	messages2 "longmen/server/internal/rpc/tencentim/messages"
	"longmen/server/internal/rpc/tencentim/room_event"
	"longmen/server/internal/rpc/tencentim/utils"
	_const "longmen/server/pkg/common/helper/const"
	"longmen/server/pkg/common/lib/bytesconv"
	"longmen/server/pkg/db/mysql"
	"longmen/server/pkg/db/mysql/db_main"
	"longmen/server/pkg/db/mysql/models/models_main"
	gCache "longmen/server/pkg/db/redis/cache"
	"time"

	"go.uber.org/zap"
)

type TxChat struct {
	logger *zap.SugaredLogger
}

func NewTxChat(log *zap.SugaredLogger) *TxChat {
	return &TxChat{
		logger: log,
	}
}

// GiftHeatCalculator 热度更新
func (t *TxChat) GiftHeatCalculator(msg []byte) bool {
	var giftHeat room_event.GiftHeat
	err := json.Unmarshal(msg, &giftHeat)
	if err != nil {
		t.logger.Error("gift heat Unmarshal error: %v", err)
		return false
	}
	user := giftHeat.User
	giftReq := giftHeat.GiftReq
	//
	roomCfg, err := cache.GetLiveConfig(user.RoomId)
	if err != nil {
		t.logger.Errorf("get room config error: %v", err)
		return false
	}

	giftType, giftPrice, err := utils.GetGiftPrice(roomCfg, int(giftReq.Giftid), int(giftReq.Count))
	if err != nil {
		t.logger.Errorf("set attenuation error: %v", err)
		return false
	}

	// 更新统计信息，记录礼物总价值和总数
	incrGiftPrice := map[string]int{
		room_event.RoomStatsGiftTotalPrice: giftPrice,
		room_event.RoomStatsGiftTotalNum:   int(giftReq.Count),
	}
	switch giftType {
	case room_event.GiftPriceTypeDiamond:
		//incrGiftPrice = map[string]int{
		//	server.RoomStatsGiftDiamondTotalPrice: giftPrice,
		//	server.RoomStatsGiftDiamondTotalNum:   quantity,
		//}
		incrGiftPrice[room_event.RoomStatsGiftDiamondTotalPrice] = giftPrice
		incrGiftPrice[room_event.RoomStatsGiftDiamondTotalNum] = int(giftReq.Count)
	}

	for key, val := range incrGiftPrice {

		err = cache.UpdateStats(key, val, user.RoomId, true)
		if err != nil {
			t.logger.Errorf("ROOM[%d]: UserSendGift() failed, %s, key : %s val:%d", user.RoomId, err, key, val)
		}
	}
	return true
}

// ClearChat 清理聊天室历史记录
func (t *TxChat) ClearChat(msg []byte) bool {
	var clearChatReq messages2.ClearMessage
	err := json.Unmarshal(msg, &clearChatReq)
	if err != nil {
		t.logger.Errorf("Unmarshal clearChat err [%v], raw data [%v]", err, bytesconv.BytesToString(msg))
		return false
	}
	m := &messages2.ClearChatMessage{
		SentMessageStruct: messages2.SentMessageStruct{Type: messages2.RoomClearChatType},
		RoomId:            clearChatReq.RoomId,
		ChatId:            clearChatReq.ChatId,
		UserId:            clearChatReq.UserId,
	}
	//t.logger.Debugf("clear:%v", m)
	db_main.DeleteEsChatHistoryById(clearChatReq.RoomId, clearChatReq.ChatId)
	err = imsdk2.GetSdk().BroadcastInterface(clearChatReq.RoomId, m, 3)
	if err != nil {
		return false
	}
	return true
}

// LoginBroadcast 匿名用户广播消息
func (t *TxChat) AnoLoginBroadcast(msg []byte) bool {
	var req messages2.EnterRoomMessage
	err := json.Unmarshal(msg, &req)
	if err != nil {
		t.logger.Errorf("login broadcast error: %v", err)
		return false
	}
	rds := global.GetRds()
	key := fmt.Sprintf(_const.REDIS_LAST_ANO_MSG_TIME, req.RoomId)
	m, _ := global.GetRds().Exists(key).Result()
	if m == 0 {
		err = imsdk2.GetSdk().BroadcastInterface(req.RoomId, req, 1)
		if err != nil {
			global.Log.Warnf("welcome ano faild:%s", err.Error())
		}
		rds.Set(key, 1, 1*time.Second) //执行完后锁1s
	}
	return true
}

// LoginBroadcast 登录广播消息
func (t *TxChat) LoginBroadcast(msg []byte) bool {
	var req messages2.EnterRoomMessage
	err := json.Unmarshal(msg, &req)
	if err != nil {
		t.logger.Errorf("login broadcast error: %v", err)
		return false
	}
	global.Log.Debugf("广播登录消息:%+v", string(msg))
	rds := global.GetRds()
	key := fmt.Sprintf(_const.REDIS_LAST_WELCOME_TIME, req.RoomId)
	m, _ := global.GetRds().Exists(key).Result()
	if m == 0 {
		err = imsdk2.GetSdk().BroadcastInterface(req.RoomId, req, 1)
		if err != nil {
			global.Log.Warnf("welcome faild:%s", err.Error())
		}
		rds.Set(key, 1, 100*time.Millisecond)
	}
	return true
}

// SubscribeAnchor 关注直播间
func (t *TxChat) SubscribeAnchor(msg []byte) bool {
	var subAnchoriteMess messages2.SubAttentanchorMess
	err := json.Unmarshal(msg, &subAnchoriteMess)
	if err != nil {
		global.Log.Errorf("SubMessage subAnchoriteMess err [%v]", err)
		return true
	}

	user := chat.GetClientUser(subAnchoriteMess.UserId)
	if user == nil {
		global.Log.Errorf("client user not exist,uid:%v", subAnchoriteMess.UserId)
		return true
	}
	global.Log.Debugf("SubscribeAnchor ,uid :%v,roomId:%v,level:%v", subAnchoriteMess.UserId, user.RoomId, user.Level)
	m := &messages2.RoomUserLoveMessage{
		SentMessageStruct: messages2.SentMessageStruct{Type: messages2.RoomUserLoveMessageType},
		ClientName:        user.ClientName,
		Content:           global.Lang.T("follow_msg"),
		Level:             user.Level,
	}
	err = imsdk2.GetSdk().BroadcastInterface(subAnchoriteMess.RoomId, m, 3)
	if err != nil {
		return false
	}
	return true
}

// UserPropsUpdate 挂件更新
func (t *TxChat) UserPropsUpdate(msg []byte) bool {
	type UidMessage struct {
		Uid int `json:"uid"`
	}
	var uidMessage UidMessage
	err := json.Unmarshal(msg, &uidMessage)
	if err != nil {
		t.logger.Errorf("SubMessage ChangePrpos  err [%v]", err)
		return false
	}
	user := chat.GetClientUser(uidMessage.Uid)
	if user == nil {
		return false
	}
	props := api.GetAPI().GetUserBackPack(uidMessage.Uid)
	user.Props = props
	chat.SetClientUser(user)
	return true
}

func (t *TxChat) SubAdminLogMessage(msg []byte) bool {
	var adminLog models_main.AdminLog
	err := json.Unmarshal(msg, &adminLog)
	if err != nil {
		t.logger.Errorf("SubMessage subAdminLogMessage  err [%v]", err)
		return false
	}
	mysql.InsertXAny(&adminLog, "adminLog")
	return true
}

// ChatHistoryToEs 聊天记录
func (t *TxChat) ChatHistoryToEs(msg []byte) bool {
	var chatHistory models_main.ChatHistory
	err := json.Unmarshal(msg, &chatHistory)
	t.logger.Debug("chatHistory: ", chatHistory)
	if err != nil {
		t.logger.Errorf("ChatRecordHandler Unmarshal Message err [%v]", err)
		return false
	}

	db_main.InsertEsChatHistory(&chatHistory)

	err = gCache.OnTaskEvent(chatHistory.Uid, _const.TASK_DAILY_CHAT, 1) //---------task 埋点--------
	if err != nil {
		t.logger.Infof("6Task9处理弹幕任务失败 err [%v]", err)
		return false
	}
	return true
}

// AllMemberPush 批量推送信息
func (t *TxChat) AllMemberPush(msg []byte) bool {
	var s imsdk2.OfflineMsgNats
	err := json.Unmarshal(msg, &s)
	if err != nil {
		t.logger.Errorf("allMemberPushHandler Unmarshal error: %v", err)
		return false
	}
	var o imsdk2.OfflineMsg

	err = o.SendOfflineMsg(s.OfflineArgs, s.Condition, s.User, s.Title, s.Content)
	if err != nil {
		t.logger.Errorf("allMemberPushHandler SendOfflineMsg error: %v", err)
		return false
	} else {
		t.logger.Infof("allMemberPushHandler: %s", bytesconv.BytesToString(msg))
	}
	return true
}

//自动聊天推送

func (t *TxChat) AutoChatPush(msg []byte) bool {
	global.Log.Debugf("收到推送消息:%v", string(msg))
	var s messages2.RoomUserSayMessageToNats
	err := json.Unmarshal(msg, &s)
	if err != nil {
		t.logger.Errorf("AutoChatPush Unmarshal error: %v", err)
		return false
	}
	if s.RoomId < 1 {
		return true
	}
	err = imsdk2.GetSdk().BroadcastInterface(s.RoomId, s, 0)
	if err != nil {
		global.Log.Errorf("err:%v", err)
		return true
	}
	return true
}
